package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.query.CarPackageAuditQuery2;
import cn.wolfcode.car.business.query.CarPackageAuditQueryObject;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.base.query.QueryObject;
import cn.wolfcode.car.common.util.StringUtils;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;



    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());

        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForList(qo);

        for (CarPackageAudit carPackageAudit : carPackageAudits) {
            carPackageAudit.setServiceItem(serviceItemService.get(carPackageAudit.getServiceItemId()));
            carPackageAudit.setAuditor(userService.get(carPackageAudit.getAuditorId()));
        }

        return new TablePageInfo<CarPackageAudit>(carPackageAudits);
    }
    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override//流程图查看
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = this.get(id);
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        InputStream inputStream=null;
        //获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion()
                .singleResult();


        BpmnModel model = repositoryService.getBpmnModel(definition.getId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //如果状态为审核中或者审核拒绝，说明还正在流程中
        if(carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS) ){
            Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());
            inputStream = generator.generateDiagram(model, activeActivityIds, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else{
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
             inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }
            return inputStream;
    }

    @Override//撤销,正在审核的商品流程
    public void cancelApply(Long id) {
//        流程撤销，服务单项状态要复原，审核记录状态改为撤销，审批流程实例要删除
        //套餐商品更变为初始化
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        Long serviceItemId = carPackageAudit.getServiceItemId();
        serviceItemService.updateByStatic(ServiceItem.AUDITSTATUS_INIT,serviceItemId);

        //审核记录状态改为撤销
        carPackageAuditMapper.updateByStart(CarPackageAudit.STATUS_CANCEL,id);

//        审批流程实例要删除
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"审核撤销");

    }

    @Override
    public TablePageInfo<CarPackageAudit> queryTodo(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());

        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForListTodo(qo);

        for (CarPackageAudit carPackageAudit : carPackageAudits) {
            ServiceItem serviceItem = serviceItemService.get(carPackageAudit.getServiceItemId());
            carPackageAudit.setServiceItem(serviceItemService.get(carPackageAudit.getServiceItemId()));
            carPackageAudit.setAuditor(userService.get(carPackageAudit.getAuditorId()));
        }

        return new TablePageInfo<CarPackageAudit>(carPackageAudits);
    }

    @Override//审批处理
    public void audit(Long id, Integer auditStatus, String info) {
        //如果是最后一个任务,要设置审核状态
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //获取当前审核人对象
        String userName = ShiroUtils.getUser().getUserName();
        //判断是同意还是拒绝,添加注解,谁谁谁同意,谁谁谁拒绝;
        //三元判断,是同意吗?
        String commentStr= auditStatus == CarPackageAudit.STATUS_PASS? userName +"同意":userName + "拒绝";
        //当前审核备注不为空的话,把审批人的审批意见添加进当前套餐审核项目的备注里
        if (StringUtils.isEmpty(info)){
            info += commentStr;
            carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+info);
        }
        //获取当前节点任务对象
        Task task = taskService.createTaskQuery()
                .processInstanceId(carPackageAuditMapper.selectByPrimaryKey(id).getInstanceId())
                .singleResult();
        //根据任务id和流程实例id去添加审批人审批意见
        taskService.addComment(task.getId(),task.getProcessInstanceId(),info);
        //设置审批人变量信息,当前处理人是谁,变量名字和数据
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        //处理任务
        taskService.complete(task.getId());
        //处理器处理任务只是做了推动作用,审批人拒绝同意还是需要靠逻辑代码实现
        //当前任务处理完了之后,要判断还有没有任务,然后根据情况给套餐单项赋予状态,给审核实例赋予状态
        //同意
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
          //判断还有没有任务
            //再次执行获取任务,上面的任务被执行后就消失了,所以再次获取任务就可以做到判断
            //通过判空来判断接下来还有没有任务
            Task nextTask = taskService.createTaskQuery()
                    .processInstanceId(carPackageAuditMapper.selectByPrimaryKey(id).getInstanceId())
                    .singleResult();
            if (nextTask==null){
                //接下来没任务,修改当前套餐审核为审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                //设置最后审核时间
                carPackageAudit.setAuditTime(new Date());
                //套餐单项状态修改为已通过
                serviceItemService.updateByStatic(ServiceItem.AUDITSTATUS_APPROVED,carPackageAudit.getServiceItemId());
            }else {
                //还有任务的话,通过activit7自带的当前执行任务环节表,去获取下一个审批人信息,塞到我们自定义的套餐流程表里
                carPackageAudit.setAuditorId(Long.valueOf(nextTask.getAssignee()));
            }
        }else {
            //拒绝,停止当前套餐审核流程,改变套单项和套餐流程的状态
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            serviceItemService.updateByStatic(ServiceItem.AUDITSTATUS_INIT,carPackageAudit.getServiceItemId());
        }

        //到这里,该处理该修改的都做了,更新套餐流程的信息,更新下个执行人信息和状态
        carPackageAuditMapper.updateAuditor(carPackageAudit);
    }

    @Override
    public TablePageInfo<CarPackageAudit> queryTodo2(CarPackageAuditQuery2 qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        qo.setName(ShiroUtils.getUser().getUserName());

        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForListTodo2(qo);

        for (CarPackageAudit carPackageAudit : carPackageAudits) {
            ServiceItem serviceItem = serviceItemService.get(carPackageAudit.getServiceItemId());
            carPackageAudit.setServiceItem(serviceItemService.get(carPackageAudit.getServiceItemId()));
            carPackageAudit.setAuditor(userService.get(carPackageAudit.getAuditorId()));
        }
        return new TablePageInfo<>(carPackageAudits);
    }


    @Override//保存
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }




    @Override//删除
    public void deleteBatch(Long ids) {

            //硬删除
            carPackageAuditMapper.deleteByPrimaryKey(ids);
    }
}
